<template>
  <div>
    <div
      class="avatar-uploader"
      :style="
        'width:' + width + 'px;height:' + height + 'px;cursor:pointer;'
      "
      @click="openImageContainer"
    >
      <img
        v-if="initImageUrl"
        :src="initImageUrl"
        :style="'width:' + width + 'px;height:' + height + 'px;'"
      >
      <img
        v-else-if="imageUrl"
        :src="imageUrl"
        :style="'width:' + width + 'px;height:' + height + 'px;'"
      >
      <i
        v-else
        class="el-icon-plus avatar-uploader-icon"
        :style="
          'width:' +
            width +
            'px;height:' +
            height +
            'px;line-height:' +
            height +
            'px;'
        "
      />
    </div>
    <el-dialog
      :visible.sync="visible"
      :modal-append-to-body="false"
      :append-to-body="true"
    >
      <template slot="title">选择图片</template>
      <el-card shadow="never">
        <div class="image-container">
          <div>
            <el-upload
              class="avatar-uploader"
              action="/admin/upload/upload"
              :headers="headers"
              :show-file-list="false"
              :on-success="handleAvatarSuccess"
              :before-upload="beforeAvatarUpload"
            >
              <i class="el-icon-plus avatar-uploader-icon" />
            </el-upload>
          </div>
          <div v-for="item in imageList" :key="item.id" class="image">
            <img :src="item.url">
            <div class="operation">
              <img
                src="@/assets/images/right.png"
                class="chooice"
                @click="chooseImage(item)"
              >
              <img
                src="@/assets/images/zoom.png"
                class="zoom"
                @click="showImage(item)"
              >
              <img
                src="@/assets/images/delete.png"
                class="delete"
                @click="deleteImage(item)"
              >
            </div>
          </div>
        </div>
      </el-card>
      <template>
        <el-pagination
          :current-page="queryParams.page"
          :page-size="queryParams.page_size"
          layout="total, prev, pager, next, jumper"
          :total="total"
          @current-change="handleCurrentChange"
        />
        <div class="footer-right">
          <el-button type="primary">确定</el-button>
        </div>
      </template>
    </el-dialog>
    <el-dialog :visible.sync="imageShowVisible" :title="imageTitle">
      <div>{{ imageInfo }}</div>
      <img :src="showImageUrl" style="max-width:100%;">
    </el-dialog>
  </div>
</template>

<script>
import { getImages, deleteImage } from '@/api/upload/index'
export default {
  props: {
    width: {
      type: String,
      default: '200'
    },
    height: {
      type: String,
      default: '200'
    },
    initImageUrl: {
      type: String,
      default: ''
    },
    isShowInSelf: {
      type: Boolean,
      default: true
    }
  },
  data() {
    return {
      visible: false,
      imageShowVisible: false,
      headers: {
        Authorization: window.sessionStorage.getItem('token')
      },
      queryParams: {
        page: 1,
        page_size: 11
      },
      total: 0,
      imageList: [],
      showImageUrl: '',
      imageTitle: '',
      imageInfo: '',
      imageUrl: '' // 没有弹出的时候显示的图片
    }
  },
  created() {
    this.getImages()
  },
  mounted() {},
  methods: {
    openImageContainer() {
      this.visible = true
    },
    async getImages() {
      const { data: res } = await getImages(this.queryParams)
      this.imageList = res.data
      this.total = res.total
    },
    handleAvatarSuccess(res) {
      this.queryParams.page = 1
      this.getImages()
    },
    beforeAvatarUpload(file) {
      const isJPG = file.type === 'image/jpeg'
      const isPng = file.type === 'image/png'
      const isLt2M = file.size / 1024 / 1024 < 2

      if (!isJPG && !isPng) {
        this.$message.error('上传头像图片只能是 JPG 或者 PNG 格式!')
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!')
      }

      return (isPng || isJPG) && isLt2M
    },
    handleCurrentChange(page) {
      this.queryParams.page = page
      this.getImages()
    },
    showImage(item) {
      console.log(item)
      this.showImageUrl = item.url
      this.imageInfo =
        '大小:' +
        (item.size / 1024).toFixed(2) +
        'K 上传时间: ' +
        this.dateFormat(item.created_at)
      this.imageTitle = item.origin_name
      this.imageShowVisible = true
    },
    async deleteImage(item) {
      this.$confirm('是否确认删除该图片?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(async() => {
          const { data: res } = await deleteImage(item.id)
          if (res.code === 1) {
            this.$message.success(res.msg)
            this.getImages()
          } else {
            this.$message.error(res.msg)
          }
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消'
          })
        })
    },
    chooseImage: function(item) {
      if (this.isShowInSelf) {
        this.imageUrl = item.url
      }
      this.visible = false
      this.$emit('choose-image', item)
    },
    clear: function() {
      this.imageUrl = ''
    },
    dateFormat: function(originVal) {
      // js 与php的区别
      originVal = originVal * 1000
      var date = new Date(originVal)
      var year = date.getFullYear()
      var month =
        date.getMonth() + 1 < 10
          ? '0' + (date.getMonth() + 1)
          : date.getMonth() + 1
      var day = date.getDate() < 10 ? '0' + date.getDate() : date.getDate()
      var hours = date.getHours() < 10 ? '0' + date.getHours() : date.getHours()
      var minutes =
        date.getMinutes() < 10 ? '0' + date.getMinutes() : date.getMinutes()
      var seconds =
        date.getSeconds() < 10 ? '0' + date.getSeconds() : date.getSeconds()
      // 拼接
      return (
        year +
        '-' +
        month +
        '-' +
        day +
        ' ' +
        hours +
        ':' +
        minutes +
        ':' +
        seconds
      )
    }
  }
}
</script>

<style lang="less" scoped>
.footer-right {
  display: flex;
  justify-content: flex-end;
  padding-top: 20px;
}
.image-container {
  display: flex;
  justify-content: flex-start;
  flex-wrap: wrap;
  .image {
    margin-right: 20px;
    margin-bottom: 20px;
    position: relative;
    img {
      width: 195px;
      height: 195px;
      padding: 1px;
      border: 1px dashed #d9d9d9;
    }
    .operation {
      img {
        display: none;
      }
    }
    &:hover .operation {
      position: absolute;
      left: 0;
      top: 0;
      right: 0;
      bottom: 0;
      background: rgba(0, 0, 0, 0.5);
      display: flex;
      justify-content: center;
      align-items: center;
      img {
        width: 30px;
        height: 30px;
        margin: 10px;
        border: none;
        display: block;
      }
    }
  }
}
.avatar-uploader {
  width: 200px;
  height: 200px;
  margin-right: 20px;
  margin-bottom: 20px;
  .avatar-uploader-icon {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    font-size: 28px;
    color: #8c939d;
    width: 190px;
    height: 190px;
    line-height: 190px;
    text-align: center;
  }
  .avatar-uploader-icon:hover {
    border-color: #409eff;
  }
  .avatar {
    max-width: 100%;
    height: 190px;
    display: block;
  }
}
</style>
